<?php
namespace app\jobs;

use app\config\Constants;
use app\models\GoodsOrder;
use app\models\Merchant;
use app\utils\QueueUtil;

/**
 * 自动接单任务
 * Class AutoAcceptJob
 * @package app\jobs
 */
class AutoAcceptJob {

    private static $handle_type = [Constants::ORDER_WAIT];

    public function execute($queue,$job){
        if($job['msg_type'] != Constants::MSG_TYPE_ORDER){
            return true;
        }
        if(!in_array($job['event_type'],self::$handle_type)){
            return true;
        }

        $order = GoodsOrder::findOne(['order_no'=>$job['data']['order_no']]);
        if(!$order){
            return false;
        }
        $merchant = Merchant::findOne(['merchant_id'=>$order->merchant_id]);
        if(!$merchant || $merchant->auto_accept == Constants::STATUS_PROHIBIT){
            return true;
        }
        //营业时间
        $range = explode("-",$merchant->business_time);
        if(date("H") < $range[0] && date("H") > $range[1]){
            return true;
        }
        $order->status = Constants::ORDER_ACCEPT;

        //发送接单消息
        return $order->update() !== false && QueueUtil::fanout(Constants::MSG_TYPE_ORDER,Constants::ORDER_ACCEPT,['order_no'=>$order->order_no],$queue);
    }
}